/*
 * 文件名：PropertyBillController.java
 * 版权：Copyright by hlst
 * 描述：
 * 修改人：liuziyu
 * 修改时间：2016年6月28日
 * 跟踪单号：
 * 修改单号：
 * 修改内容：
 */

package com.zcsy.manage.owner.controller.property;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zcsy.commons.constants.Constants;
import com.zcsy.commons.constants.OwnerConstants;
import com.zcsy.commons.model.RequestJson;
import com.zcsy.commons.unique.UniqueNumberUtils;
import com.zcsy.commons.util.DateUtils;
import com.zcsy.manage.model.base.CellHouse;
import com.zcsy.manage.model.base.CommonImg;
import com.zcsy.manage.model.base.CommonToken;
import com.zcsy.manage.model.property.CarBill;
import com.zcsy.manage.model.property.CarBillDetail;
import com.zcsy.manage.model.property.FeeBill;
import com.zcsy.manage.model.property.FeeBillConfig;
import com.zcsy.manage.model.property.FeeBillDetail;
import com.zcsy.manage.model.property.RepairInfo;
import com.zcsy.manage.model.system.User;
import com.zcsy.manage.owner.common.StringUtil;
import com.zcsy.manage.owner.service.common.IOCommonTokenService;
import com.zcsy.manage.owner.service.system.IOUserService;
import com.zcsy.manage.service.base.ICellHouseService;
import com.zcsy.manage.service.base.ICommonImgService;
import com.zcsy.manage.service.property.ICarBillDetailService;
import com.zcsy.manage.service.property.ICarBillService;
import com.zcsy.manage.service.property.IFeeBillDetailService;
import com.zcsy.manage.service.property.IFeeBillService;
import com.zcsy.manage.service.property.IRepairInfoService;
import com.zcsy.manage.service.system.IUserService;

/**
 * @Title: PropertyBillController.java
 * @Package： com.zcsy.manage.owner.controller.property
 * @Description: 物业费停车费控制层
 * @author liuziyu liuziyuwri@foxmail.com
 * @Copyright: 2016 武汉恒数利通软件有限公司 All rights reserved.
 * @date 2016年6月28日
 * @version 1.0
 * @see JDK1.7.0_75
 * @since
 */
@Controller
@RequestMapping(value = "propertyBill")
public class PropertyBillController {
    
    @Autowired
    private IOCommonTokenService commonTokenService;

    @Autowired
	private IOUserService ouserService;
    
    @Autowired
    private IUserService userService;
    
    @Autowired
    private ICarBillService carBillService;
    
    @Autowired
    private ICarBillDetailService carBillDetailService;

    @Autowired
    private ICellHouseService cellHouseService;
    
    @Autowired
    private IFeeBillDetailService feeBillDetailService;
    
    @Autowired
    private IFeeBillService feeBillService;
    
    @Autowired
	private IOCommonTokenService commomTokenService;
    
    @Autowired
    private IRepairInfoService repairInfoService;
    
    @Autowired
    private ICommonImgService commonImgService;
	
	/**
	 * @Method: propertyFeePaymentList
	 * @Description 物业缴费-缴费记录列表
	 * @param pNo 分页页数
	 * @param token
	 * @return orderNum      String 缴费单号 
	 * 		   totalAmount   double 缴费总额 
	 * 		   ownerHouse    String 房屋
	 *         period        String 缴费时间段
	 *         paymentStatus int    缴费状态
	 * @throws RuntimeException
	 * @author liuziyu liuziyuwri@foxmail.com
	 * @date 2016年6月28日
	 * @see
	 */
	@RequestMapping(value = "propertyFeePaymentList")
	@ResponseBody
	public RequestJson propertyFeePaymentList(Integer pNo, String token)
			throws RuntimeException {

		RequestJson result = new RequestJson();

		// 指定默认为首页
		if (pNo == null || pNo < OwnerConstants.PAGE_NO) {
			pNo = OwnerConstants.PAGE_NO;
		}

		// 缴费信息
		List<FeeBillDetail> feeBillList = null;

		CommonToken commonToken = commonTokenService.selectByToken(token);
		// 根据token查询登录名
		String loginname = commonToken.getAccount();
		// 根据登录名查询用户
		User user = ouserService.selectByLoginName(loginname);
		// 根据用户查询业主ID
		String userID = user.getId();
		
		// 获取业主房屋信息
		List<CellHouse> houses = cellHouseService
				.getListByOwnerIdAndState(userID, OwnerConstants.NORMAL_HOUSE_STATE);
		
		// 获取房屋id的集合
		List<String> housesID = new ArrayList<String>();
		Iterator<CellHouse> iterator = houses.iterator(); 
        while(iterator.hasNext()){ 
        	CellHouse house = (CellHouse) iterator.next(); 
        	if(house != null){
        		housesID.add(house.getId());
        	}
        }  

        // 此处添加PageHelper将会走拦截器，进行分页，分页方法只针对紧跟着PageHelper的查询方法有效
        PageHelper.startPage(pNo, OwnerConstants.PAGE_SIZE);
        
        // 根据房屋id查询账单列表
        feeBillList = feeBillService.selectFeeBillByHouseId(housesID);

        // 写入房屋的名称
		Iterator<FeeBillDetail> iteratorfeeBillList = feeBillList.iterator();
		while (iteratorfeeBillList.hasNext()) {
			FeeBillDetail detail = (FeeBillDetail) iteratorfeeBillList.next();
			detail.setHouseFullName(detail.getCellName()
					+ detail.getRegionName() + detail.getBuildingName()
					+ detail.getUnitName() + detail.getName());
		}
        
		// 分页
		PageInfo<FeeBillDetail> feeBillListP = new PageInfo<FeeBillDetail>(feeBillList);
		result.setObj(feeBillListP);
		result.setSuccess(true);
		result.setResultCode(OwnerConstants.RESULT_CODE_SUCCESS);
		result.setMsg("成功获取数据");

		return result;
	}
	
	/**
	 * @Method: propertyFeePaymentDetail
	 * @Description 物业缴费-缴费记录详单
	 * @param token
	 * 		  billID 账单id
	 * @return  paymentTime 	String 	缴费时间
	 *			totalAmount 	double 	合计金额
	 *			ownerHouse 	    String 	房屋
	 *			period 	   	    String 	缴费时间段
	 *			houseArea 	    double 	房屋面积
	 *			price 	        double 	物业费单价
	 *			baseNumber   	int 	物业费基数
	 *			paymentStatus   bool 	缴费状态
	 *			paymentType 	int 	缴费方式
	 *			operator 	    String 	操作人
	 * @throws RuntimeException
	 * @author liuziyu liuziyuwri@foxmail.com
	 * @date 2016年6月28日
	 * @see
	 */
	@RequestMapping(value = "propertyFeePaymentDetail")
	@ResponseBody
	public RequestJson propertyFeePaymentDetail(String billID, String token)
			throws RuntimeException {
		
		RequestJson result = new RequestJson();

		// 根据房屋id查询账单详情
		FeeBillDetail feeBillDetail = feeBillDetailService
				.selectByPrimaryKey(billID);
		// 写入房屋的名称
		if (feeBillDetail != null) {
			feeBillDetail.setHouseFullName(feeBillDetail.getCellName()
					+ feeBillDetail.getRegionName()
					+ feeBillDetail.getBuildingName()
					+ feeBillDetail.getUnitName() + feeBillDetail.getName());
			result.setObj(feeBillDetail);
			result.setSuccess(true);
			result.setResultCode(OwnerConstants.RESULT_CODE_SUCCESS);
			result.setMsg("成功获取数据");

		} else {
			result.setSuccess(false);
			result.setResultCode(OwnerConstants.RESULT_CODE_FALSE);
			result.setMsg("获取数据失败");
		}

		return result;
	}

	/**
     * @Method: submitParkingfee
     * @Description 停车费缴费提交接口
     * @param month           int     缴纳停车费的月数
     *        carNo           String  车牌号
     *        startDateByUser String    用户输入的起始时间
     *        billContent      String  发票内容
     *        token
     * @return 
     * @author liuziyu
     * @date 2016年6月29日
     * @see
     */
	@RequestMapping(value = "submitParkingfee")
    @ResponseBody
	public RequestJson submitParkingfee(String token, Integer month,
			String startDateByUser, String carNo,
			String billContent) {

		// TODO 车辆类型car_type由海康接口返回

		// TODO startDate由海康接口返回
		Date startDate = new Date();
		
		// TODO unitPrice停车费单价由海康接口返回
		Integer unitPrice = 200;
		
		// 停车费单价转型成BigDecimal
		BigDecimal unitPriceBigDecimal = new BigDecimal(unitPrice);
		
		RequestJson result = new RequestJson();

		// startDate转为Date类型
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date startDateByUserDate = new Date();
		try {
			startDateByUserDate = sdf.parse(startDateByUser);
			startDate = sdf.parse(sdf.format(startDate));
		} catch (ParseException e) {
			e.printStackTrace();
		}

		// 如果用户输入的起始时间不早于起始时间
		if (!startDateByUserDate.before(startDate)) {
			
			CarBill carBill = new CarBill();
			CarBillDetail carBillDetail = new CarBillDetail();
			CommonToken tokenInfo = new CommonToken();
			
			// 根据carNo查house_id
			carBill = carBillService.selectByCarNo(carNo);
			String houseId = carBill.getHouseId();
			
			// 根据house_id查cell_id
			CellHouse cellHouse = cellHouseService.selectByPrimaryKey(houseId);
			String cellId = cellHouse.getCellId();
			
			// 根据token查tokenInfo所有信息，取出loginname即为account
			tokenInfo = commomTokenService.selectByToken(token);
			String userAccount = tokenInfo.getAccount();
			
			// 从历史记录中查询carType
			CarBill carBillPast = carBillService.selectByCarNo(carNo);
			Integer carType = carBillPast.getCarType();
			
			// 向停车费账单插入信息
			String carId = UniqueNumberUtils.get18UniqueNumber();
			carBill.setId(carId);
			carBill.setHouseId(houseId);
			carBill.setCarNo(carNo);
			carBill.setCellId(cellId);
			carBill.setUserAccount(userAccount);
			carBill.setCarType(carType);
			carBill.setGenerateWay(OwnerConstants.OPERATOR_TYPE_OWNER);
			carBill.setSendTime(DateUtils.gettimestamp());
			carBillService.insert(carBill);

			// 向停车费账单详情插入信息
			carBillDetail.setId(UniqueNumberUtils.get18UniqueNumber());
			carBillDetail.setCarId(carId);
			carBillDetail.setCarNo(carNo);
			carBillDetail.setBillType(OwnerConstants.INVOICE_PERSON);
			carBillDetail.setBillTitle(billContent);

			carBillDetail.setMonth(month);
			carBillDetail.setUnitPrice(unitPriceBigDecimal);
			// 计算金额
			BigDecimal payMonthsBigDecimal = new BigDecimal(month);
			BigDecimal money = unitPriceBigDecimal.multiply(payMonthsBigDecimal) ;
			carBillDetail.setMoney(money);
			carBillDetail.setStartDate(startDateByUserDate);
			// 计算结束时间
			Calendar cal = Calendar.getInstance();
			cal.setTime(startDateByUserDate);
			cal.add(Calendar.MONTH, month);
			cal.add(Calendar.DATE, -1);
			Date endDate = cal.getTime();
			carBillDetail.setEndDate(endDate);
			
			carBillDetail.setState(OwnerConstants.STATE_PRE_PAYING);
			carBillDetail.setGenerateWay(OwnerConstants.STATE_PRE_PAYING);
			carBillDetail.setOperatorType(OwnerConstants.OPERATOR_TYPE_OWNER);
			carBillDetail.setOperatorAccount(userAccount);
			carBillDetail.setPayWay(Constants.PAY_WAY_UNPAY);
			
			// 根据登录名查询用户
			String userName = ouserService.selectByLoginName(userAccount).getUsername();
			carBillDetail.setOperator(userName);
			carBillDetail.setCreateTime(DateUtils.gettimestamp());
			carBillDetailService.insert(carBillDetail);
			
			result.setSuccess(true);
			result.setResultCode(OwnerConstants.RESULT_CODE_SUCCESS);
			result.setMsg("缴费提交成功！");
			result.setObj(carBillDetail);
			
		} else {
			result.setSuccess(false);
			result.setResultCode(OwnerConstants.RESULT_CODE_FALSE);
			result.setMsg("起始时间不得早于上次缴费的结束时间！");
		}
		

		return result;

	}
	
    /**
     * @Method: submitPayment
     * @Description 缴物业费提交接口
     * @param token
     * @param payMonths 物业费的月数
     * @param payHousing 房屋ID
     * @param startDate 起始时间
     * @param invoiceContent 发票抬头
     * @return 
     * @author liuziyu liuziyuwri@foxmail.com
     * @date 2016年6月29日
     * @see 
     */
	@RequestMapping(value = "submitPayment")
	@ResponseBody
	public RequestJson submitPayment(String token, Integer payMonths,
			String payHousing, String invoiceContent) {

		RequestJson result = new RequestJson();
		try{
		// 从token获取当前账户信息
		CommonToken tokenInfo = commonTokenService.selectByToken(token);
		User user = ouserService.selectByLoginName(tokenInfo.getAccount());
		FeeBillDetail recordDetail = feeBillDetailService.submitFeeOrder(payHousing, payMonths, invoiceContent, user);
		
		if (recordDetail != null) {
			result.setSuccess(true);
			result.setResultCode(OwnerConstants.RESULT_CODE_SUCCESS);
			result.setMsg("成功提交账单");
			result.setObj(recordDetail);
		} else {
			result.setSuccess(false);
			result.setResultCode(OwnerConstants.RESULT_CODE_FALSE);
			result.setMsg("操作失败，请稍后重试");
		}
		}catch(Exception e){
			e.printStackTrace();
			result.setSuccess(false);
			result.setResultCode(OwnerConstants.RESULT_CODE_FALSE);
			result.setMsg("操作失败，请稍后重试");
		}

		return result;
	}
	
	@RequestMapping(value = "submitOverDuePayment")
	@ResponseBody
	public RequestJson submitOverDuePayment(String token, String billId){
		RequestJson result = new RequestJson();
		try {
			// 从token获取当前账户信息
			CommonToken tokenInfo = commonTokenService.selectByToken(token);
			User user = ouserService.selectByLoginName(tokenInfo.getAccount());
			FeeBillDetail recordDetail = feeBillDetailService
					.selectByPrimaryKey(billId);
			if (recordDetail == null
					|| recordDetail.getState() != OwnerConstants.STATE_OWING_MONEY) {
				result.setSuccess(false);
				result.setResultCode(OwnerConstants.RESULT_CODE_FALSE);
				result.setMsg("账单已失效");
				return result;
			}

			recordDetail.setOperatorType(OwnerConstants.OPERATOR_TYPE_OWNER);
			recordDetail.setOperator(user.getId());
			recordDetail.setOperatorAccount(user.getLoginname());
			feeBillDetailService.updateByPrimaryKey(recordDetail);
			
			result.setSuccess(true);
			result.setResultCode(OwnerConstants.RESULT_CODE_SUCCESS);
			result.setMsg("成功提交账单");
			result.setObj(recordDetail);
		} catch (Exception e) {
			e.printStackTrace();
			result.setSuccess(false);
			result.setResultCode(OwnerConstants.RESULT_CODE_FALSE);
			result.setMsg("操作失败，请稍后重试");
		}
		
		return result;
	}
    
    /**
     * @Method: submitPaymentRange
     * @Description 缴物业费提交接口（计算缴费起始时间）
     * @param token
     * @param payHousing 房屋ID
     * @return startDate 起始时间
     * @author liuziyu liuziyuwri@foxmail.com
     * @date 2016年7月1日
     * @see 
     */
    @RequestMapping(value = "submitPaymentRange")
    @ResponseBody
    public RequestJson submitPaymentRange(String token , String payHousing) {
    	
		RequestJson result = new RequestJson();
		// 根据房屋id查询最后一条成功的详细记录
		FeeBillDetail lastFeeBillDetail = feeBillDetailService
				.selectLastBill(payHousing);
		if (lastFeeBillDetail != null) {
			Calendar cal = Calendar.getInstance();
			cal.setTime(lastFeeBillDetail.getEndDate());
			
			//结束时间大于开始时间日期才加1，等于的时候不加（初始化和导入的初始数据）
			if(lastFeeBillDetail.getEndDate().after(lastFeeBillDetail.getStartDate())){
				cal.add(Calendar.DATE, 1);
			}
			
			Date startDate = cal.getTime();
			
			result.setObj(startDate);
			result.setSuccess(true);
			result.setResultCode(OwnerConstants.RESULT_CODE_SUCCESS);
			result.setMsg("查询起始时间成功");
			
		} else {
			result.setSuccess(false);
			result.setResultCode(OwnerConstants.RESULT_CODE_FALSE);
			result.setMsg("未查询到历史账单信息");
		}
    	
    	return result;
    }
    
    /**
     * 获取车辆停车费起始时间
     * @param token
     * @param carId
     * @return
     * @author: zt
     * @date: 2016年8月29日
     */
    @RequestMapping(value = "getParkingPayStartTime")
    @ResponseBody
    public RequestJson getParkingPayStartTime(String token , String carNo, String cellId) {
    	
		RequestJson result = new RequestJson();
		Map<String ,Object> params = new HashMap<String ,Object>();
		params.put("carNo", carNo);
		params.put("cellId", cellId);
		// 根据房屋id查询最后一条成功的详细记录
		CarBillDetail lastCarBillDetail = carBillDetailService.selectLastBill(params);
		Date startDate = null;
		if (lastCarBillDetail != null) {
			Date lastEndDate = lastCarBillDetail.getEndDate();
			// 最后一条记录的结束时间加一天作为新的起始时间
			Calendar cal = Calendar.getInstance();
			cal.setTime(lastEndDate);
			cal.add(Calendar.DATE, 1);
			startDate = cal.getTime();
			Date today = new Date();
			if(startDate.before(new Date())){
				startDate = today;
			}
			
		} else {
			startDate = new Date();
		}
		result.setObj(startDate);
		result.setSuccess(true);
		result.setResultCode(OwnerConstants.RESULT_CODE_SUCCESS);
		result.setMsg("查询起始时间成功");
    	return result;
    }
    
    /**
     * @Method: parkingfeeDetail
     * @Description 停车费账单详情
     * @param carID 停车账单id
     * @param token
     * @return  payTime 	    String 	缴费时间
	 *			totalAmount 	double 	合计金额
	 *			carID 			String 	停车账单id
	 *			carNo 			String 	车牌号
	 *			ownerHouse 	    String 	房屋
	 *			startDate 	   	String 	起始时间
	 *			endDate 	   	String 	结束时间
	 *			unitPrice 	    double 	停车费单价
	 *			paymentStatus   bool 	缴费状态
	 *			paymentType 	int 	缴费方式
	 *			operator 	    String 	操作人
     * @throws RuntimeException 
     * @author liuziyu liuziyuwri@foxmail.com
     * @date 2016年7月1日
     * @see 
     */
	@RequestMapping(value = "parkingFeeDetail")
	@ResponseBody
	public RequestJson parkingFeeDetail(String carID, String token)
			throws RuntimeException {
		RequestJson result = new RequestJson();

		// 根据汽车账单id查询账单详情
		CarBillDetail carBillDetail = carBillDetailService.selectByPrimaryKey(carID);

		if (carBillDetail != null) {
			// 根据车牌号查询房屋信息
			CarBill carBill = carBillService.selectByCarNo(carBillDetail
					.getCarNo());
			String houseID = carBill.getHouseId();
			CellHouse cellHouse = cellHouseService.selectByPrimaryKey(houseID);
			// 写入房屋的名称
			if (cellHouse != null) {
				carBillDetail.setHouseFullName(cellHouse.getCellName()
						+ cellHouse.getRegionName()
						+ cellHouse.getBuildingName() + cellHouse.getUnitName()
						+ cellHouse.getName());
				result.setObj(carBillDetail);
				result.setSuccess(true);
				result.setResultCode(OwnerConstants.RESULT_CODE_SUCCESS);
				result.setMsg("成功获取数据");
			} else {
				result.setObj(carBillDetail);
				result.setSuccess(false);
				result.setResultCode(OwnerConstants.RESULT_CODE_FALSE);
				result.setMsg("未能获取房屋信息");
			}

		} else {
			result.setSuccess(false);
			result.setResultCode(OwnerConstants.RESULT_CODE_FALSE);
			result.setMsg("获取停车账单数据失败");
		}

		return result;
	}
	   
    /**
     * @Method: parkingFeePaymentList
     * @Description 停车费缴费-缴费记录列表
     * @param pNo
     * @param token
     * @return orderNum      String 缴费单号 
     *         totalAmount   double 缴费总额 
     *         ownerHouse    String 房屋
     *         carNo         String 车牌
     *         period        String 缴费时间段
     *         paymentStatus int    缴费状态
     * @throws RuntimeException 
     * @author liuziyu liuziyuwri@foxmail.com
     * @date 2016年7月1日
     * @see 
     */
    @RequestMapping(value = "parkingFeePaymentList")
    @ResponseBody
    public RequestJson parkingFeePaymentList(Integer pNo, String token)
            throws RuntimeException {
        RequestJson result = new RequestJson();

        // 指定默认为首页
        if (pNo == null || pNo < OwnerConstants.PAGE_NO) {
            pNo = OwnerConstants.PAGE_NO;
        }

        // 缴费信息
        List<CarBillDetail> carBillList = null;

        CommonToken commonToken = commonTokenService.selectByToken(token);
        // 根据token查询登录名
        String loginname = commonToken.getAccount();
        // 根据登录名查询用户
        User user = ouserService.selectByLoginName(loginname);
        // 根据用户查询业主ID
        String userID = user.getId();

        /**
         * modified by hubing 20160831 start
         * 
         * reason：查新条件错误，应查询当前用户所绑定车辆的缴费信息
         */
//        // 获取业主房屋信息
//        List<CellHouse> houses = cellHouseService.getListByOwnerIdAndState(
//                userID, OwnerConstants.NORMAL_HOUSE_STATE);
//
//        // 获取房屋id的集合
//        List<String> housesID = new ArrayList<String>();
//        Iterator<CellHouse> iterator = houses.iterator();
//        while (iterator.hasNext()) {
//            CellHouse house = (CellHouse) iterator.next();
//            if(house != null){
//                housesID.add(house.getId());
//            }
//        }

        // 此处添加PageHelper将会走拦截器，进行分页，分页方法只针对紧跟着PageHelper的查询方法有效
        PageHelper.startPage(pNo, OwnerConstants.PAGE_SIZE);

        carBillList = carBillService.selectCarBillByHouseId(userID);
        // modified by hubing 20160831 end

        // 写入房屋的名称
        Iterator<CarBillDetail> iteratorCarBillList = carBillList.iterator();
        while (iteratorCarBillList.hasNext()) {
            CarBillDetail detail = (CarBillDetail) iteratorCarBillList.next();
            detail.setHouseFullName(detail.getCellName()
                    + detail.getRegionName() + detail.getBuildingName()
                    + detail.getUnitName() + detail.getName());
        }

        // 分页
        PageInfo<CarBillDetail> carBillListP = new PageInfo<CarBillDetail>(carBillList);
        result.setObj(carBillListP);
        result.setSuccess(true);
        result.setResultCode(OwnerConstants.RESULT_CODE_SUCCESS);
        result.setMsg("成功获取数据");
        return result;
    }
	
	/**
     * @Method: submitRepairInfo
     * @Description 提交报修问题
     * @param token           String     
     *        title           String    标题
     *        contactor       String    联系人
     *        ownerId         String    业主ID
     *        contactorPhone  String    联系电话
     *        content         String    内容
     *        level           int       危害程度
     *        photo           String    图片
     * @return result
     * @author yangfan 373188993@qq.com
     * @date 2016年6月29日
     * @see
     */

    @RequestMapping(value = "submitRepairInfo")
    @ResponseBody
    public RequestJson submitRepairInfo(String token, String title, String contactor,
                                        String contactorPhone, String content, int level,
                                        String photo,String houseId) {

        RequestJson result = new RequestJson();
        RepairInfo repairInfo = new RepairInfo();
        CommonImg commonimgRecord = new CommonImg();

        try {
            if ((title != null) && (contactor != null) && (contactorPhone != null)
                && (content != null)) {
                
                String[] photoUrl = null;
                CommonToken commonToken = commonTokenService.selectByToken(token);
                // 根据token查询登录名
                String loginname = commonToken.getAccount();
                // 根据登录名查询用户
                User user = ouserService.selectByLoginName(loginname);
                // 根据用户查询业主ID
                String userID = user.getId();
                // 生成18位id
                String id = UniqueNumberUtils.get18UniqueNumber();
                
                repairInfo.setTitle(title);
                repairInfo.setId(id);
                repairInfo.setContactor(contactor);
                repairInfo.setOwnerId(userID);
                repairInfo.setHouseId(houseId);
                repairInfo.setContactorPhone(contactorPhone);
                repairInfo.setContent(content);
                repairInfo.setLevel(level);
                repairInfo.setCreateTime(DateUtils.gettimestamp());
                repairInfo.setState(OwnerConstants.SUBMIT_REPAIR_STATE);
                
                int flag = repairInfoService.insert(repairInfo);
                if (flag == OwnerConstants.INSERT_SUCCESS) {
                    
                    if(!StringUtils.isEmpty(photo)){
                        //将得到的photo拆分
                        photoUrl = photo.split(",");
                        // 设置图片插入对象属性值
                        for (String item : photoUrl) {
                            commonimgRecord.setId(UniqueNumberUtils.get18UniqueNumber());
                            commonimgRecord.setUrl(item);
                            commonimgRecord.setName("报修");
                            commonimgRecord.setObjType(Constants.OWNER_REPAIRINFO);
                            commonimgRecord.setObjId(id);
                            commonimgRecord.setSendTime(DateUtils.getTimestamp());
                            commonImgService.insert(commonimgRecord);
                        }
                    }
                    
                    result.setSuccess(true);
                    result.setResultCode(OwnerConstants.RESULT_CODE_SUCCESS);
                    result.setMsg("报修成功");
                } else if (flag == OwnerConstants.INSERT_FALSE) {
                    result.setSuccess(false);
                    result.setResultCode(OwnerConstants.RESULT_CODE_FALSE);
                    result.setMsg("报修失败");
                }
            } else {
                result.setSuccess(false);
                result.setResultCode(OwnerConstants.RESULT_CODE_FALSE);
                result.setMsg("插入数据不可为空");
            }
        } catch (Exception e) {
            result.setSuccess(false);
            result.setResultCode(OwnerConstants.RESULT_EXCEPTION_FALSE);
            result.setMsg("网络异常");
        }
        return result;

    }
    
    /**
     * @Method: overdueBill
     * @Description 我的账单列表（每个房屋只有一条欠费记录）
     * @param token
     * @return  houseFullName 	String 	房屋全名
     * 			owingMoney 		String 	欠费金额
     *			billID 			String 	账单号
     *			startDate 		date 	起始时间
     *			endDate 		date 	结束时间
     * @author liuziyu liuziyuwri@foxmail.com
     * @date 2016年7月5日
     * @see 
     */
	@RequestMapping(value = "overdueBill")
	@ResponseBody
	public RequestJson overdueBill(String token) {

		RequestJson result = new RequestJson();

		CommonToken commonToken = commonTokenService.selectByToken(token);
		// 根据token查询登录名
		String loginname = commonToken.getAccount();
		// 根据登录名查询用户
		User user = ouserService.selectByLoginName(loginname);
		// 根据用户查询业主ID
		String userID = user.getId();

		// 获取业主房屋信息
		List<CellHouse> houses = cellHouseService.getListByOwnerIdAndState(
				userID, OwnerConstants.NORMAL_HOUSE_STATE);

		// 获取房屋id的集合
		List<String> housesID = new ArrayList<String>();
		Iterator<CellHouse> iterator = houses.iterator();
		while (iterator.hasNext()) {
			CellHouse house = (CellHouse) iterator.next();
			if(house != null){
				housesID.add(house.getId());
			}
		}
		// 根据房屋id查询欠费账单
		List<FeeBillDetail> feeBillDetail = feeBillDetailService
				.selectFeeBillDetailByHouseId(housesID);

		if (feeBillDetail != null && feeBillDetail.size() > 0) {
			// 写入房屋的名称
			Iterator<FeeBillDetail> iteratorfeeBill = feeBillDetail.iterator();
			while (iteratorfeeBill.hasNext()) {
				FeeBillDetail detail = (FeeBillDetail) iteratorfeeBill.next();
				if (detail.getName() != null) {
					detail.setHouseFullName(detail.getCellName()
							+ detail.getRegionName() + detail.getBuildingName()
							+ detail.getUnitName() + detail.getName());

				}
			}
			result.setObj(feeBillDetail);
			result.setSuccess(true);
			result.setResultCode(OwnerConstants.RESULT_CODE_SUCCESS);
			result.setMsg("成功获取数据！");
		}else {
			result.setSuccess(false);
			result.setResultCode(OwnerConstants.RESULT_CODE_FALSE);
			result.setMsg("未查询到欠费记录！");
		}

		return result;

	}
	
	/**
	 * @Method: getParkingfee
	 * @Description 获取停车费单价
	 * @param token
	 * @param carNo 车牌号
	 * @return parkingPrice 	double 	停车费单价
	 * @author liuziyu liuziyuwri@foxmail.com
	 * @date 2016年7月5日
	 * @see 
	 */
	@RequestMapping(value = "getParkingfee")
	@ResponseBody
	public RequestJson getParkingfee(String token, String carNo) {

		RequestJson result = new RequestJson();
	
		//TODO 调用海康的接口
		
		result.setObj(200.0);
		result.setSuccess(true);
		result.setResultCode(OwnerConstants.RESULT_CODE_SUCCESS);
		result.setMsg("成功获取数据");
		
		return result;
	}
	
	/**
	 * @Method: getCarStartDate
	 * @Description 获取停车费起始时间
	 * @param token
	 * @param carNo 车牌号
	 * @return startDate 	date 	起始时间
	 * @author liuziyu liuziyuwri@foxmail.com
	 * @date 2016年7月5日
	 * @see 
	 */
	@RequestMapping(value = "getCarStartDate")
	@ResponseBody
	public RequestJson getCarStartDate(String token, String carNo) {
		
		RequestJson result = new RequestJson();
		
		//TODO 调用海康的接口
		
		result.setObj(new Date());
		result.setSuccess(true);
		result.setResultCode(OwnerConstants.RESULT_CODE_SUCCESS);
		result.setMsg("成功获取数据");
		
		return result;
	}
	
	/**
	 * @Method: getCarNoByHouse
	 * @Description 通过房屋查找车辆 
	 * @param token
	 * @param houseId 房屋id
	 * @return 房屋id和车牌号
	 * @author liuziyu liuziyuwri@foxmail.com
	 * @date 2016年7月5日
	 * @see 
	 */
	@RequestMapping(value = "getCarNoByHouse")
	@ResponseBody
	public RequestJson getCarNoByHouse(String token, String houseId) {

		RequestJson result = new RequestJson();

		// 将housesID分成数组
		//String[] houseIdArray = housesID.split(",");
		// 根据house_id查carNo
		List<CarBill> carBill = carBillService.selectCarBillByOneHouseId(houseId);

		if (carBill != null && carBill.size() > 0) {
			result.setObj(carBill);
			result.setSuccess(true);
			result.setResultCode(OwnerConstants.RESULT_CODE_SUCCESS);
			result.setMsg("成功获取数据");
			
		} else {
			result.setSuccess(false);
			result.setResultCode(OwnerConstants.RESULT_CODE_FALSE);
			result.setMsg("未查询到车牌信息");

		}

		return result;
	}
	
	 /**
     * @Method: overdueCarBill
     * @Description 停车费缴费我的账单列表接口（每个车辆只有一条最近缴费记录） 
     * @param token
     * @return  houseFullName 	String 	房屋全名
     * 			owingMoney 		String 	欠费金额
     *			carID 			String 	账单号
     *			startDate 		date 	起始时间
     *			endDate 		date 	结束时间
     *			carNo			String  车牌号
     * @author liuziyu liuziyuwri@foxmail.com
	 * @throws ParseException 
     * @date 2016年7月7日
     * @see 
     */
	@RequestMapping(value = "overdueCarBill")
	@ResponseBody
	public RequestJson overdueCarBill(String token) {

		RequestJson result = new RequestJson();

		try {
		    CommonToken commonToken = commonTokenService.selectByToken(token);
		    // 根据token查询登录名
		    String loginname = commonToken.getAccount();
		    // 根据登录名查询用户
		    User user = ouserService.selectByLoginName(loginname);
		    // 根据用户查询业主ID
		    String userID = user.getId();
		    
		    // 获取业主房屋信息
		    List<CellHouse> houses = cellHouseService.getListByOwnerIdAndState(
		        userID, OwnerConstants.NORMAL_HOUSE_STATE);
		    
		    // 获取房屋id的集合
		    List<String> housesID = new ArrayList<String>();
		    Iterator<CellHouse> iterator = houses.iterator();
		    while (iterator.hasNext()) {
		        CellHouse house = (CellHouse) iterator.next();
		        if(house != null){
		            housesID.add(house.getId());
		        }
		    }
		    // 根据房屋id查询一条最近缴费记录
		    List<CarBillDetail> carBillDetail = carBillDetailService
		        .selectCarBillDetailByHouseId(housesID);
		    
		    if (carBillDetail != null && carBillDetail.size() > 0) {
		        // 写入房屋的名称
		        Iterator<CarBillDetail> iteratorCarBill = carBillDetail.iterator();
		        while (iteratorCarBill.hasNext()) {
		            CarBillDetail detail = (CarBillDetail) iteratorCarBill.next();
		            if (detail.getName() != null) {
		                detail.setHouseFullName(detail.getCellName()
		                    + detail.getRegionName() + detail.getBuildingName()
		                    + detail.getUnitName() + detail.getName());
		                
		                //计算距离停车费到期天数，设置提醒状态
		                Calendar cal = Calendar.getInstance();    
		                Date endDate = detail.getEndDate() ;  
//		                Date now = DateUtils.getStartTimeOfDay();
		                Date now = cal.getTime();
		                
		                //设置到期的日期为当天的23：59：59：999
		                cal.setTime(endDate);    
		                cal.set(Calendar.HOUR, 23);  
                        cal.set(Calendar.MINUTE, 59);  
                        cal.set(Calendar.SECOND, 59);  
                        cal.set(Calendar.MILLISECOND, 999);  
		                long endDateTime = cal.getTimeInMillis();
		                
		                //获取当日开始的时间
		                cal.setTime(now);    
		                long nowTime = cal.getTimeInMillis();   
		                
		                long betweenDays = (endDateTime-nowTime)/(1000*3600*24);
		                
		                //修正日期显示不正确的情况
		                if(endDateTime < nowTime) {
		                    betweenDays = betweenDays - 1 ;
		                }
		                detail.setRemainDays(String.valueOf(betweenDays));
		                
		                //判断天数，设置停车费到期提醒状态 1:未到期 2：即将到期 3：已到期
                        if (betweenDays > OwnerConstants.CLOSE_TO_ENDDAYS_TIME) {
                            detail.setRemindState(OwnerConstants.FARAWAY_TO_ENDDAYS);
                        } else if ((betweenDays < OwnerConstants.CLOSE_TO_ENDDAYS_TIME || betweenDays == OwnerConstants.CLOSE_TO_ENDDAYS_TIME)
                                   && (betweenDays > OwnerConstants.IS_ENDDAYS_TIME || betweenDays == OwnerConstants.IS_ENDDAYS_TIME)) {
                            detail.setRemindState(OwnerConstants.CLOSE_TO_ENDDAYS);
                        } else {
                            detail.setRemindState(OwnerConstants.BEYOND_ENDDAYS);
                        }
		            }
		        }
		        result.setObj(carBillDetail);
		        result.setSuccess(true);
		        result.setResultCode(OwnerConstants.RESULT_CODE_SUCCESS);
		        result.setMsg("成功获取数据");
		    }else {
		        result.setSuccess(false);
		        result.setResultCode(OwnerConstants.RESULT_CODE_FALSE);
		        result.setMsg("未成功获取最新一次缴费记录");
		    }
            
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setResultCode(OwnerConstants.RESULT_EXCEPTION_FALSE);
            result.setMsg("网络异常！");
        }

		return result;
	}
	
	/**
	 * @Method: carBindHouse
	 * @Description 车牌绑定房屋
	 * @param token
	 * @param houseId 房屋id
	 * @param carNo 车牌
	 * @param carType 车辆类型  1-小型车 2-大型车 0-其他
	 * @param cellId 小区id
	 * @return 
	 * @author liuziyu liuziyuwri@foxmail.com
	 * @date 2016年7月18日
	 * @see 
	 */
	@RequestMapping(value = "carBindHouse")
	@ResponseBody
	public RequestJson carBindHouse(String token, String houseId, String carNo, Integer carType, String cellId) {

		RequestJson result = new RequestJson();
		
		// 根据车牌号查询是否绑定了房屋
		CarBill carBill = carBillService.selectByBindingCarNo(carNo);
		// 如果未绑定房屋
		if (carBill == null ) {
			CarBill carBillUnbunding = carBillService.selectByUnbundingCarNo(carNo);
			CarBill record = new CarBill();
			record.setId(UniqueNumberUtils.get18UniqueNumber());
			record.setCellId(cellId);
			record.setHouseId(houseId);
			record.setCarNo(carNo);
			
			CommonToken commonToken = commonTokenService.selectByToken(token);
			// 根据token查询登录名
			String loginname = commonToken.getAccount();
			// 根据登录名查询用户
			User user = ouserService.selectByLoginName(loginname);
			// 根据用户查询业主ID
			String userID = user.getId();
			record.setOwnerId(userID);
			record.setCarType(carType);
			record.setGenerateWay(OwnerConstants.OPERATOR_TYPE_OWNER);
			record.setUserAccount(loginname);
			record.setSendTime(DateUtils.gettimestamp());
			record.setState(OwnerConstants.CAR_NUMBER_BOUND);
			
			// 如果以前解绑过该房屋
			 if (carBillUnbunding != null && carBillUnbunding.getBuildingId() == houseId){
				carBillService.updateBindingState(carBillUnbunding.getId());
				result.setObj(record);
				result.setSuccess(true);
				result.setResultCode(OwnerConstants.RESULT_CODE_SUCCESS);
				result.setMsg("成功重绑该车辆");

			// 如果以前车辆解绑过其他房屋或未绑定房屋
			} else {
				carBillService.insert(record);
				result.setObj(record);
				result.setSuccess(true);
				result.setResultCode(OwnerConstants.RESULT_CODE_SUCCESS);
				result.setMsg("成功绑定车辆");
			}
			// 如果已绑定此房屋
		} else if (carBill != null && carBill.getBuildingId() == houseId){
			result.setSuccess(false);
			result.setResultCode(OwnerConstants.RESULT_CODE_FALSE);
			result.setMsg("已绑定此车辆");

		}else {
			result.setSuccess(false);
			result.setResultCode(OwnerConstants.RESULT_CODE_FALSE);
			result.setMsg("此车辆已绑定其他房屋");
		}
		return result;
	}
	
    /**
     * @Method: unbundingCar
     * @Description 批量解除车辆绑定
     * @param token
     * @param carNo
     *            车牌 逗号隔开
     * @return result
     * @author yangfan 373188993@qq.com
     * @date 2016年7月18日
     * @see
     */
    @RequestMapping(value = "unbundingCar")
    @ResponseBody
    public RequestJson unbundingCar(String token, String carNo) {

        RequestJson result = new RequestJson();
        try {
            // 将传入的一串carNo分开并存入数组
            String[] carNoArray = carNo.split(",");

            // 循环解绑
            for (String carNoSingle : carNoArray) {

                // 根据车牌号查询绑定房屋的信息
                CarBill carBill = carBillService.selectByBindingCarNo(carNoSingle);
                CarBill record = new CarBill();

                // 如果查询到有绑定的信息，则进行解绑操作
                if (carBill != null) {
                    // 更新解绑信息
                    record.setCarNo(carNoSingle);
                    record.setState(OwnerConstants.CAR_NUMBER_UNBOUND);
                    record.setUpdateTime(DateUtils.gettimestamp());
                    int flag = carBillService.updateStateByCarNo(record);

                    // 更新成功OR失败返回相应信息
                    if (flag == OwnerConstants.UPDATE_SUCCESS) {
                        result.setSuccess(true);
                        result.setResultCode(OwnerConstants.RESULT_CODE_SUCCESS);
                        result.setMsg("解除绑定成功！");
                    } else {
                        result.setSuccess(false);
                        result.setResultCode(OwnerConstants.RESULT_CODE_FALSE);
                        result.setMsg("解除绑定失败！");
                    }
                } else {
                    result.setSuccess(false);
                    result.setResultCode(OwnerConstants.RESULT_CODE_FALSE);
                    result.setMsg("未查询到绑定信息！");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setResultCode(OwnerConstants.RESULT_EXCEPTION_FALSE);
            result.setMsg("网络异常！");
        }
        return result;
    }
	
    /**
     * @Method: getCarList
     * @Description 显示车辆列表
     * @param token
     * @return result 房屋及对应车辆信息
     * @author yangfan 373188993@qq.com
     * @date 2016年7月18日
     * @see
     */
    @RequestMapping(value = "getCarList")
    @ResponseBody
    public RequestJson getCarList(String token) {

        RequestJson result = new RequestJson();
        try {

            // 通过token查找OwnerId
            CommonToken commonToken = commonTokenService.selectByToken(token);
            // 根据token查询登录名
            String loginname = commonToken.getAccount();
            // 根据登录名查询用户
            User user = userService.selectByLoginName(loginname);
            // 根据用户查询业主ID
            String ownerId = user.getId();

            // 通过业主id查询房屋地址信息及车牌
            List<CellHouse> record = cellHouseService.selectHouseInfoAndCarNoByOwnerId(ownerId);
            if (!record.isEmpty()) {
                result.setSuccess(true);
                result.setResultCode(OwnerConstants.RESULT_CODE_SUCCESS);
                result.setMsg("获取信息成功！");
                result.setObj(record);
            } else {
                result.setSuccess(false);
                result.setResultCode(OwnerConstants.RESULT_CODE_FALSE);
                result.setMsg("获取信息失败！");
            }

        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setResultCode(OwnerConstants.RESULT_EXCEPTION_FALSE);
            result.setMsg("网络异常！");
        }
        return result;
    }
    
    /**
     * @Method: getFeeMinimum
     * @Description 物业费最低缴费月数获取接口
     * @param token
     * @param cellId  小区id
     * @return result
     * @author yangfan 373188993@qq.com
     * @date 2016年7月18日
     * @see
     */
    @RequestMapping(value = "getFeeMinimum")
    @ResponseBody
    public RequestJson getFeeMinimum(String cellId , String token) {
        
        RequestJson result = new RequestJson();
        
        try {
            FeeBillConfig feeBillConfig= feeBillService.getFeeBillConfigByCellId(cellId);
            if (feeBillConfig != null) {
                result.setSuccess(true);
                result.setResultCode(OwnerConstants.RESULT_CODE_SUCCESS);
                result.setMsg("获取小区物业费配置成功！");
                result.setObj(feeBillConfig);
            } else {
                result.setSuccess(false);
                result.setResultCode(OwnerConstants.RESULT_CODE_FALSE);
                result.setMsg("获取信息失败！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setResultCode(OwnerConstants.RESULT_EXCEPTION_FALSE);
            result.setMsg("网络异常！");
        }
        return result;
    }
}
